import ctypes
import os
import time
import serial
import win32con

# 打开串口
if __name__ == '__main__':
    serial = serial.Serial('COM5', 9600, timeout=0.5)
    if serial.isOpen() :
        print("open success")
    else :
        print("open failed")

# 发送报文
def send(send_data):
    if (serial.isOpen()):
        # serial.write(send_data.encode('utf-8'))  # 编码
        serial.write(send_data)  # 编码
        print("发送成功", send_data)
    else:
        print("发送失败！")

# 调用发送函数
#默认绿灯
#发报文1为红色
data_send = [0x01, 0x05, 0x00, 0x00, 0xFF, 0x00, 0x8C, 0x3A]
#发报文2为绿色
data_send2 = [0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0xCD, 0xCA]

while True:
    f = open('connect.txt', 'r')
    txt = f.read(1024)
    if txt == 'control':
        print('txt为：' + txt)
        #关绿灯，亮红灯
        send(data_send)
        time.sleep(0.1)
        print('已打开红灯')
        os.system(
            '"C:\Program Files\iTunes\iTunes.exe" D:\PycharmProjects\HelmetDetectionSystem\MPAPHelmetDetectionSystem\航车运行中.mp3')
        ctypes.windll.user32.MessageBoxTimeoutW(0, '注意：行车操作人员并未佩戴安全帽\n',
                                                'Warning', win32con.MB_YESNO, 0, 2000)
        time.sleep(5.5)
        # break
    if txt == 'helmet' or txt == 'h' or txt == 'null':
        print('txt为：' + txt)
        # 关红灯，开绿灯
        send(data_send2)
        time.sleep(0.1)
        print('已打开绿灯')